from exceptions import ValueError
from django import forms, template
from django.http import HttpResponseRedirect
from customtags.decorators import block_decorator
from pirate_core.views import HttpRedirectException, namespace_get

register = template.Library()
block = block_decorator(register)

get_namespace = namespace_get("hello")

@block
def hello_tag(context, nodelist, *args, **kwargs):

    ###
    ### First, in order to limit all changes to the context to the scope of this block, 
    ### call it's push() method, which deliniates a limited scope.  Next, grab the namespace
    ### that we will be using for the context.
    ###

    context.push()
    namespace = get_namespace(context)

    ###
    ### Next, build the local context variables in response to the request
    ### The key word arguments to the tag will be made available via the kwargs dict
    ###

    user    = kwargs.get('user', None)
    session = kwargs.get('session', None)
    POST    = kwargs.get('POST', None)
    path    = kwargs.get('path', "")

    # a simple demonstration of populating the namespace
    namespace['path'] = path

    if user.is_authenticated():
        namespace['username'] = user.username 
    else:
        namespace['username'] = "is not defined.  You have to login first"
    if session:
        namespace['session_id'] = session.session_key
        session_values = []
        for key in session.keys():
            pair = (key, session[key])
            session_values.append(pair)
        namespace['session_values'] = session_values

    ###
    ### Now, check to see if a form submission has been made that might need to be 
    ### processed.  If there is POST dictionary, then check that the form being submitted
    ### is for this module, and then process it. Note the use of the hidden field "form_id"
    ### which is implemented on SessionForm to ensure that the POST is intended to be 
    ### processed here--this is the only difference with how you would process a form in a 
    ### standard view.
    ###

    if POST and POST.get("form_id") == "hello-tag":
        form = SessionForm(POST)
        if form.is_valid():
            key = form.cleaned_data["key"]
            value = form.cleaned_data["value"]
            if session:
                session[key] = value
            raise HttpRedirectException(HttpResponseRedirect(path))
    else:
        form = SessionForm()
    namespace['form'] = form

    ###
    ### Finally: The business logic has been run and completed, so the contents of this 
    ### tag block should be rendered and returned so as to be incorporated with the 
    ### rest of the page.  Note that context.pop() is called in order to exit the 
    ### scope of the block once the contents are rendered.
    ###

    output = nodelist.render(context)
    context.pop()
    return output


class SessionForm(forms.Form):
    key = forms.CharField(max_length=50)
    value = forms.CharField(max_length=50)
    form_id = forms.CharField(widget=forms.HiddenInput(), initial="hello-tag")
